import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { instance } from '..';

export const getAccountById = createAsyncThunk(
  'account/getAccountById',
  async (accountId, thunkAPI) => {
    try {
      const response = await instance.get(`/accounts/${accountId}`);
      return response;
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  },
);


export const getAccountAll = createAsyncThunk(
  'account/getAccountAll',
  async (_, thunkAPI) => {
    try {
      const response = await instance.get("/accounts/search?from=0&to=1000");
      return response;
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  },
);

export const putAccountById = createAsyncThunk(
  'account/putAccountById',
  async (accountId, thunkAPI) => {
    try {
      const response = await instance.put(`/accounts/${accountId}`);
      return response;
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  },
);


export const deleteAccountById = createAsyncThunk(
  'account/deleteAccountById',
  async (accountId, thunkAPI) => {
    try {
      const response = await instance.delete(`/accounts/${accountId}`);
      return response;
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  },
);


export const updateUser = createAsyncThunk('products/updateUser', async (userInfo, thunkAPI) => {
  try {
    const response = await instance.put(`/accounts/${userInfo.accountId}`, userInfo.body);
    return response;
  } catch (error) {
    return thunkAPI.rejectWithValue(error);
  }
});


const initialState = {
  account: {},
  isLoading: false,
  accounts: [],
};

export const accountSlice = createSlice({
  name: 'account',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getAccountById.pending, (state) => {
      state.isLoading = false
    });
    builder.addCase(getAccountById.fulfilled, (state, { payload }) => {
      state.isLoading = true
      state.account = payload;
    });
    builder.addCase(getAccountAll.pending, (state, { payload }) => {
      state.isLoading = false
    });
    builder.addCase(getAccountAll.fulfilled, (state, { payload }) => {
      state.isLoading = true
      state.accounts = payload;
    });
  },
});

export const {} = accountSlice.actions;

export default accountSlice.reducer;
